package com.sgb.kjwl.view.widget;

import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.AdmixtureEntity;
import com.sgb.kjwl.model.entity.ConcreteDetailEntity;
import com.sgb.kjwl.model.entity.ConcreteFilterEntity;
import com.sgb.kjwl.model.entity.ConcreteParamEntity;
import com.sgb.kjwl.utils.NumberFormatUtils;
import com.sgb.kjwl.view.ui.activity.material.ConcreteDetailActivity2;
import com.sgb.kjwl.view.ui.activity.self.publish.STDetailActivity;
import com.sgb.kjwl.view.ui.adapter.material.ConcreteAdmixAdapter;
import com.sgb.kjwl.view.ui.adapter.material.ConcreteParamsAdapter;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.PopViewHolder;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.ScreenUtil;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GoodSSTWindow extends BasePopWindow implements View.OnClickListener {
    public ConcreteAdmixAdapter admixAdapter;
    public ConcreteParamsAdapter strengthAdapter;
    public static int TYPE_SELF = 1;//个人中心详情页显示
    public static int TYPE_SHOP = 2;//商品详情页显示
    public ConcreteParamsAdapter serviceAdapter;
    public ConcreteParamsAdapter gradtionAdapter;
    private ConcreteDetailEntity data;
    RecyclerView listStrength, listService, listGradtion, listAdmix;
    FrameLayout ivAdd, ivMinus;
    TextView etNum, name, shopPrice;
    LinearLayout root_layout, ll_strength, ll_admix, ll_service, ll_gradtion;
    RelativeLayout count_layout;
    TextView tv_close;
    TextView tv_all_price;
    OptionsPickerView businessOption;
    int type;
    String singlePrice = "0";

    public GoodSSTWindow(Context context, int type) {
        super(context, DIR_DOWN_UP);
        this.type = type;
    }

    @Override
    protected int popLayout() {
        return R.layout.pop_goods_st;
    }

    @Override
    protected void initView(PopViewHolder holder) {
        root_layout = holder.getPop().findViewById(R.id.root_layout);
        ll_strength = holder.getPop().findViewById(R.id.ll_strength);
        ll_admix = holder.getPop().findViewById(R.id.ll_admix);
        ll_service = holder.getPop().findViewById(R.id.ll_service);
        ll_gradtion = holder.getPop().findViewById(R.id.ll_gradtion);
        count_layout = holder.getPop().findViewById(R.id.count_layout);
        listStrength = holder.getPop().findViewById(R.id.list_strength);
        listService = holder.getPop().findViewById(R.id.list_service);
        listGradtion = holder.getPop().findViewById(R.id.list_gradtion);
        listAdmix = holder.getPop().findViewById(R.id.list_admix);
        ivAdd = holder.getPop().findViewById(R.id.iv_add);
        ivMinus = holder.getPop().findViewById(R.id.iv_minus);
        etNum = holder.getPop().findViewById(R.id.et_num);
        name = holder.getPop().findViewById(R.id.name);
        shopPrice = holder.getPop().findViewById(R.id.tv_price);
        tv_close = holder.getPop().findViewById(R.id.tv_close);
        tv_all_price = holder.getPop().findViewById(R.id.tv_all_price);
        ivAdd.setOnClickListener(this);
        ivMinus.setOnClickListener(this);
        tv_close.setOnClickListener(this);
        tv_close.setText("确认");
    }

    private void showAdmixParam(RecyclerView view, List<AdmixtureEntity> data) {
        view.setLayoutManager(new GridLayoutManager(mContext, 4));
        admixAdapter = new ConcreteAdmixAdapter(mContext, data);
        view.setAdapter(admixAdapter);
        admixAdapter.setOnItemClick(new AdapterOnItemClick<AdmixtureEntity>() {
            @Override
            public void onItemClick(AdmixtureEntity admixtureEntity, int position) {
                if (admixtureEntity.getSpec().size() == 2) {
                    if (admixAdapter.getSelect().get(position) == 0) {
                        admixAdapter.setSelect(position, 1);
                    } else {
                        admixAdapter.setSelect(position, 0);
                    }
                    admixAdapter.notifyDataSetChanged();
                    getPrice();
                } else {
                    showUnitPop(admixtureEntity, position);
                }
            }
        });
    }

    private void showUnitPop(AdmixtureEntity admixtureEntity, int position) {
        if (businessOption != null && businessOption.isShowing()) {

            businessOption.dismiss();

        }

        businessOption = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                admixAdapter.setSelect(position, options1);
                admixAdapter.notifyDataSetChanged();
                getPrice();
            }
        }).setDecorView(root_layout).build();

        businessOption.setPicker(admixtureEntity.getSpec());
        businessOption.setTitleText(admixtureEntity.getAdmixtureName());
        businessOption.setSelectOptions(admixAdapter.getSelect().get(position));
        businessOption.show();
    }

    private ConcreteParamsAdapter showParams(RecyclerView view, List<ConcreteFilterEntity> data) {
        view.setLayoutManager(new GridLayoutManager(mContext, 4));
        ConcreteParamsAdapter adapter = new ConcreteParamsAdapter(mContext, data);
        view.setAdapter(adapter);
        adapter.setOnItemClick(new AdapterOnItemClick<ConcreteFilterEntity>() {
            @Override
            public void onItemClick(ConcreteFilterEntity concreteFilterEntity, int position) {
                adapter.setSelect(position);
                adapter.notifyDataSetChanged();
                getPrice();
            }
        });
        return adapter;
    }

    public void setData(ConcreteDetailEntity data) {
        this.data = data;
        if (data.getStrengthList() != null && data.getStrengthList().size() > 0) {
            ll_strength.setVisibility(View.VISIBLE);
            strengthAdapter = showParams(listStrength, data.getStrengthList());
        } else {
            ll_strength.setVisibility(View.GONE);
        }
        if (data.getServiceList() != null && data.getServiceList().size() > 0) {
            ll_service.setVisibility(View.VISIBLE);
            serviceAdapter = showParams(listService, data.getServiceList());
        } else {
            ll_service.setVisibility(View.GONE);
        }
        if (data.getGradationList() != null && data.getGradationList().size() > 0) {
            ll_gradtion.setVisibility(View.VISIBLE);
            gradtionAdapter = showParams(listGradtion, data.getGradationList());
        } else {
            ll_gradtion.setVisibility(View.GONE);
        }
        if (data.getAdmixtureList() != null && data.getAdmixtureList().size() > 0) {
            ll_admix.setVisibility(View.VISIBLE);
            showAdmixParam(listAdmix, data.getAdmixtureList());
        } else {
            ll_admix.setVisibility(View.GONE);
        }
        name.setText(data.getTitle());
        if (type == TYPE_SELF) {
            count_layout.setVisibility(View.GONE);
        }
        getPrice();
    }


    /**
     * 请求显示的价格（带筛选条件单价）
     * 强度等级：strongFactId
     * 外加剂：admixtureFactIds []
     * 服务：serviceId
     * 配置：gradationId
     * 商品id：no
     */
    private void getPrice() {
        if (type == TYPE_SHOP) {
            ConcreteParamEntity concreteParamEntity = new ConcreteParamEntity();
            if (strengthAdapter != null && strengthAdapter.getSelect() != -1) {
                concreteParamEntity.setStrongFactId(strengthAdapter.getDatas().get(strengthAdapter.getSelect()).getId());
            } else {
                concreteParamEntity.setStrongFactId("");
            }
            if (serviceAdapter != null && serviceAdapter.getSelect() != -1) {
                concreteParamEntity.setServiceId(serviceAdapter.getDatas().get(serviceAdapter.getSelect()).getId());
            } else {
                concreteParamEntity.setServiceId("");
            }
            if (gradtionAdapter != null && gradtionAdapter.getSelect() != -1) {
                concreteParamEntity.setGradationId(gradtionAdapter.getDatas().get(gradtionAdapter.getSelect()).getId());
            } else {
                concreteParamEntity.setGradationId("");
            }
            concreteParamEntity.setNo(data.getNo());
            if (admixAdapter != null && admixAdapter.getSelect() != null) {
                HashMap<Integer, Integer> select = admixAdapter.getSelect();
                ArrayList<String> strings = new ArrayList<>();
                for (int i = 0; i < select.size(); i++) {
                    if (select.get(i) != 0) {
                        strings.add(admixAdapter.getDatas().get(i).getSpec().get(select.get(i)).getId());
                    }
                }
                concreteParamEntity.setAdmixtureFactIds(strings);
            } else {
                concreteParamEntity.setAdmixtureFactIds(new ArrayList<>());
            }
            getPrice(concreteParamEntity);
        } else {
            String yxgg = "";
            String strongFactPrice = "0.00";
            if (strengthAdapter != null && strengthAdapter.getSelect() != -1) {
                strongFactPrice = strengthAdapter.getDatas().get(strengthAdapter.getSelect()).getPrice();
                yxgg = strengthAdapter.getDatas().get(strengthAdapter.getSelect()).getName() + "、";
            }

            String servicePrice = "0.00";
            if (serviceAdapter != null && serviceAdapter.getSelect() != -1) {
                servicePrice = serviceAdapter.getDatas().get(serviceAdapter.getSelect()).getPrice();
                yxgg += serviceAdapter.getDatas().get(serviceAdapter.getSelect()).getName() + "、";
            }
            String gradtionPrice = "0.00";
            if (gradtionAdapter != null && gradtionAdapter.getSelect() != -1) {
                gradtionPrice = gradtionAdapter.getDatas().get(gradtionAdapter.getSelect()).getPrice();
                yxgg += gradtionAdapter.getDatas().get(gradtionAdapter.getSelect()).getName() + "、";
            }

            String admixPrice = "0.00";
            if (admixAdapter != null && admixAdapter.getSelect() != null) {
                HashMap<Integer, Integer> select = admixAdapter.getSelect();
                if (select != null) {
                    for (int i = 0; i < select.size(); i++) {
                        if (select.get(i) != 0) {
                            admixPrice = admixAdapter.getDatas().get(i).getSpec().get(select.get(i)).getPrice();
                            if (admixAdapter.getDatas().get(i).getSpec().size() != 2) {
                                yxgg += admixAdapter.getDatas().get(i).getSpec().get(select.get(i)).getName() + "、";
                            } else {
                                yxgg += admixAdapter.getDatas().get(i).getAdmixtureName() + "、";
                            }
                        }
                    }
                }
            }
            BigDecimal b1 = new BigDecimal(admixPrice);
            BigDecimal b2 = new BigDecimal(strongFactPrice);
            BigDecimal b3 = new BigDecimal(servicePrice);
            BigDecimal b4 = new BigDecimal(gradtionPrice);
            Double totalPrice = b1.add(b2).add(b3).add(b4).doubleValue();
            DecimalFormat decimalFormat = new DecimalFormat("#0.00");
            shopPrice.setText("¥" + decimalFormat.format(totalPrice) + "/立方米");
            ((STDetailActivity) mContext).showPrice(totalPrice.toString());
            if (totalPrice > 0) {
                ((STDetailActivity) mContext).setYXGG(yxgg);
            }
        }
    }

    private void setYXGG() {
        String yxgg = "";
        String strengthStr = strengthAdapter != null && strengthAdapter.getSelect() != -1 ? strengthAdapter.getDatas().get(strengthAdapter.getSelect()).getName() : "";
        String serviceStr = serviceAdapter != null && serviceAdapter.getSelect() != -1 ? serviceAdapter.getDatas().get(serviceAdapter.getSelect()).getName() : "";
        String gradtionStr = gradtionAdapter != null && gradtionAdapter.getSelect() != -1 ? gradtionAdapter.getDatas().get(gradtionAdapter.getSelect()).getName() : "";
        yxgg = strengthStr + "、" + serviceStr + "、" + gradtionStr;
        if (admixAdapter != null && admixAdapter.getSelect() != null) {
            HashMap<Integer, Integer> select = admixAdapter.getSelect();
            for (int i = 0; i < select.size(); i++) {
                if (select.get(i) != 0) {
                    if (admixAdapter.getDatas().get(i).getSpec().size() != 2) {
                        yxgg += "、" + admixAdapter.getDatas().get(i).getSpec().get(select.get(i)).getName();
                    } else {
                        yxgg += "、" + admixAdapter.getDatas().get(i).getAdmixtureName();
                    }
                }
            }
        }
        ((ConcreteDetailActivity2) mContext).setYXGG(yxgg);
    }

    public void getPrice(ConcreteParamEntity data) {
        APIManager.getInstance().getMaterialAPI().getConcretePrice(data).enqueue(new Callback<BaseEntity<ConcreteParamEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<ConcreteParamEntity>> call, Response<BaseEntity<ConcreteParamEntity>> response) {
                if (response.body() == null || !"ok".equals(response.body().getState())) {
                    return;
                }
                shopPrice.setText(response.body().getData().getTotalPrice());
                setYXGG();
                ((ConcreteDetailActivity2) mContext).showPrice(response.body().getData().getTotalPrice());
                String totalPrice = response.body().getData().getTotalPrice();
                String[] splitPrice = totalPrice.split("元");
                singlePrice = splitPrice[0].replace("￥", "");
                BigDecimal allBigDecimal = new BigDecimal(singlePrice).multiply(new BigDecimal(etNum.getText().toString().trim()));
                tv_all_price.setText("¥" + NumberFormatUtils.formatAmtNoUseGroup(Float.valueOf(allBigDecimal.toString())));
            }

            @Override
            public void onFailure(Call<BaseEntity<ConcreteParamEntity>> call, Throwable t) {

            }
        });
    }

    /***
     * 采购数量
     * @return
     */
    public int getPurchaseCount() {
        return Integer.parseInt(etNum.getText().toString());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_close:
                dismiss();
                break;
            case R.id.iv_add:
                int i = Integer.parseInt(etNum.getText().toString());
                etNum.setText(String.valueOf(i + 1));
                BigDecimal allBigDecimalAdd = new BigDecimal(singlePrice).multiply(new BigDecimal(etNum.getText().toString().trim()));
                tv_all_price.setText("¥" + NumberFormatUtils.formatAmtNoUseGroup(Float.valueOf(allBigDecimalAdd.toString())));
                break;
            case R.id.iv_minus:
                int num = Integer.parseInt(etNum.getText().toString());
                etNum.setText(String.valueOf(num > 1 ? num - 1 : 1));
                BigDecimal allBigDecimalMinus = new BigDecimal(singlePrice).multiply(new BigDecimal(etNum.getText().toString().trim()));
                tv_all_price.setText("¥" + NumberFormatUtils.formatAmtNoUseGroup(Float.valueOf(allBigDecimalMinus.toString())));
                break;
            default:
                break;

        }
    }

    @Override
    public void showDownPopwindow(View view, boolean alpha) {
        boolean hasStrengthData = null != strengthAdapter && null != strengthAdapter.getDatas() && strengthAdapter.getDatas().size() > 0;
        boolean hasServiceData = null != serviceAdapter && null != serviceAdapter.getDatas() && serviceAdapter.getDatas().size() > 0;
        boolean hasGradData = null != gradtionAdapter && null != gradtionAdapter.getDatas() && gradtionAdapter.getDatas().size() > 0;

        int calHeight =  hasStrengthData || hasServiceData || hasGradData ?
                (int) (ScreenUtil.getDisplayHeight() * 0.85) : (int) (ScreenUtil.getDisplayHeight() * 0.45);
        setHeight(calHeight);
        super.showDownPopwindow(view, alpha);
    }

}
